# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(ggrepel)
library(ropls)
library(pROC)
library(egg)
library(randomForest)
library(Boruta)
library(magrittr)
library(optparse)
library(tidyverse)
library(extrafont)

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

option_list <- list(
  make_option("--i", default = "AllMet_Raw.txt", type = "character", help = "metabolite data file"),
  make_option("--g", default = "group.txt", type = "character", help = "sample group file"),
  make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file"),
  make_option("--pc", default = "", type = "character", help = "config file")
)
opt <- parse_args(OptionParser(option_list = option_list))
font_import(paths = c("/usr/share/fonts/myFonts"),recursive =F, prompt = F)

options(digits = 3)

args <- commandArgs(trailingOnly = F)
scriptPath <- dirname(sub("--file=", "", args[grep("--file", args)]))
source(str_c(scriptPath, "/parse_config.R"))
fontFamily <- configGet(plotConfigData, "fontFamily")
baseFamily <- fontFamily

parent <- paste0("./")
createWhenNoExist(parent)

fileName <- "boruta.RData"
if (!file.exists(fileName)) {
  quit(status = 0)
}else {
  load(fileName)
}

sortData <- borutaRs$ImpHistory %>%
  t() %>%
  as.data.frame() %>%
  rownames_to_column("Metabolite") %>%
  rowwise() %>%
  do({
    result <- as.data.frame(.)
    data <- result[-1] %>%
      unlist() %>%
      discard(~is.infinite(.x))
    median <- median(data, na.rm = T)
    result$median <- median
    result
  }) %>%
  arrange(median) %>%
  as.data.frame()

sortNames <- sortData$Metabolite

decLelvels <- c("Shadow", "Rejected", "Tentative", "Confirmed")

shadow <- configGet(plotConfigData, "shadow")
rejected <- configGet(plotConfigData, "rejected")
tentative <- configGet(plotConfigData, "tentative")
confirmed <- configGet(plotConfigData, "confirmed")

fillColors <- setNames(c(shadow, rejected, tentative, confirmed), decLelvels)

head(borutaRs$ImpHistory)

decData <- borutaRs$finalDecision %>%
  as.data.frame() %>%
  rownames_to_column("Metabolite") %>%
  set_colnames(c("Metabolite", "decision"))

imp <- borutaRs$ImpHistory %>%
  t() %>%
  as.data.frame() %>%
  rownames_to_column("Metabolite") %>%
  gather("Sample", "Value", -Metabolite) %>%
  left_join(decData, by = c("Metabolite")) %>%
  mutate_at(vars("decision"), function(x) {
    ifelse(is.na(x), "Shadow", as.character(x))
  }) %>%
  mutate(Metabolite = factor(Metabolite, levels = sortNames)) %>%
  mutate(decision = factor(decision, levels = decLelvels)) %>%
  as.data.frame()

p <- ggplot(imp, mapping = aes(x = Metabolite, y = Value, fill = decision)) +
  ylab("Importance") +
  xlab("") +
  theme_bw(base_size = 8.8, base_family = baseFamily) +
  theme(axis.text.x = element_text(angle = 45, size = 9, hjust = 1, vjust = 1), legend.position = 'top',
        legend.text = element_text(size = 9), legend.title = element_text(size = 11),
        axis.text.y = element_text(size = 8.8), axis.title.y = element_text(size = 11),
        axis.title.x = element_text(size = 12), panel.border = element_rect(size = 0.75)
  ) +
  geom_boxplot() +
  scale_fill_manual("", values = fillColors)

pdfFileName <- paste0(parent, "/Decision_Boxplot.pdf")

outFileName <- paste0(parent, "/Decision_Info.csv")
outData <- read_csv(outFileName)

rowNum <- nrow(outData) + 3
defaultWidth <- max(2 + (rowNum - 10) * 0.25, 2) + 2

finalWidth <- getFinalWidth(width, defaultWidth, opt$pc)

p <- getBasicPlotArg(p)

if (!is.na(legendTitle)) {
  p <- p +
    guides(fill = guide_legend(title = legendTitle))
}

ggsave(limitsize = FALSE, pdfFileName, p, width = finalWidth, height = height)









